package com.cskaoyan.javase.object._3equals._1basic;

/**
 * equals方法的使用细节1
 * equals方法实现排它性时,有两个选择:
 *      1.严格的,使用getClass,只要不是同种类型,一定返回false
 *      2.宽松一点,使用instanceof关键字
 *          引用 instanceof 类名(抽象类名类名/接口名)
 *          判断引用所指向的对象是否是后面类名的对象,或者子类对象
 *          如果用instanceof实现排它性,会更宽松一点
 *          因为它允许方法传入子类对象
 *
 *          当引用等于null,引用 instanceof 任意类名
 *          就直接返回false
 *
 * @since 11:26
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    public static void main(String[] args) {
        /*Teacher t1 = new Teacher(18, 10000);
        Teacher t2 = new Teacher(18, 10000);
        System.out.println(t1 == t2);
        System.out.println(t1.equals(t2));

        System.out.println("-----------------");
        TeacherSon ts = new TeacherSon(18, 10000);
        System.out.println(ts == t1);
        System.out.println(t1.equals(ts));*/

        // String str = null;
        // System.out.println(str.length());
        // System.out.println(str);
        // System.out.println(str == str);

        Teacher t = new Teacher(18, 50000);
        TeacherSon ts = new TeacherSon(18, 50000);
        System.out.println(t.equals(ts));
        System.out.println(ts.equals(t));

        TeacherSon ts2 = new TeacherSon(18, 50000, 666);
        System.out.println(t.equals(ts2));
    }

}

class Teacher {
    int age;
    double salary;

    public Teacher(int age, double salary) {
        this.age = age;
        this.salary = salary;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        // 判断obj引用所指向的对象不是Student类的对象或者子类对象
        if (!(obj instanceof Teacher)) {
            return false;
        }

        /*if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }*/
        Teacher target = (Teacher) obj;
        if (this.age != target.age) {
            return false;
        }
        return this.salary == target.salary;
    }
}

class TeacherSon extends Teacher {
    int num;
    public TeacherSon(int age, double salary) {
        super(age, salary);
    }

    public TeacherSon(int age, double salary, int num) {
        super(age, salary);
        this.num = num;
    }

    /*@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof TeacherSon)) return false;
        if (!super.equals(o)) return false;
        TeacherSon that = (TeacherSon) o;
        return num == that.num;
    }*/

    /*@Override
    public int hashCode() {
        return num;
    }*/
}